package org.vt.ece4564.pcw.textinclass;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.content.Intent;
import android.os.AsyncTask;

import android.util.Log;
import android.widget.Toast;

public class LoginRequest extends AsyncTask<Void, Void, Void> {

	private String username_;
	private String password_;
	private String phoneID_;
	private LoginActivity loginActivity_;
	
	private final String URL = "http://pcw-textinclass.appspot.com/login";
	
	private String responseString_ = "";
	private Cookie cookie_;
	private boolean authenticated_ = false;
	
	public LoginRequest(String username, String password, String phoneID, LoginActivity loginActivity) {
		super();
		username_ = username;
		password_ = password;
		phoneID_ = phoneID;
		loginActivity_ = loginActivity;
	}
	
	@Override
	protected Void doInBackground(Void... params) {
		try {
			
			HttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost(URL);
			CookieStore cookies = new BasicCookieStore();
			HttpContext localContext = new BasicHttpContext();
			localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);
			
			List<NameValuePair> data = new ArrayList<NameValuePair>();
			
			data.add(new BasicNameValuePair("username", username_));
			data.add(new BasicNameValuePair("password", password_));
			data.add(new BasicNameValuePair("phoneID", phoneID_));
			
			HttpEntity entity = new UrlEncodedFormEntity(data);
			
			post.setEntity(entity);
			
			HttpResponse response = client.execute(post, localContext);
			
			if (response.getStatusLine().getStatusCode() != 200) {
				Log.d("LoginRequestError", response.getStatusLine().toString());
				return null;
			}
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			
			String line;
			
			while ((line = reader.readLine()) != null) {
				responseString_ += line;
			}
			
			if (responseString_.equals("Success")) {
				authenticated_ = true;
			
				for (Cookie c : cookies.getCookies()) {
					String name = c.getName();
				
					if (name.equals("loggedIn")) {
						cookie_ = c;
						break;
					}
				}
			}
			
		} catch (Exception e) {
			Log.d("LoginRequestErrorException", e.toString());
		}
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		if (authenticated_) {
			String cookieValue = cookie_.getValue();
			String[] cookieValues = cookieValue.split(":");
			
			if (cookieValues[2].equals("1")) {
				Intent intent = new Intent(loginActivity_, PostContactsActivity.class);
				intent.putExtra("cookieName", cookie_.getName());
				intent.putExtra("cookieValue", cookie_.getValue());
				loginActivity_.startActivity(intent);
			}
			else {
				Intent intent = new Intent(loginActivity_, LoggedInActivity.class);
				intent.putExtra("cookieName", cookie_.getName());
				intent.putExtra("cookieValue", cookie_.getValue());
				loginActivity_.startActivity(intent);
			}
		}
		else {
			loginActivity_.resetScreen();
			
			Toast toast = Toast.makeText(loginActivity_.getApplicationContext(),
					responseString_, Toast.LENGTH_SHORT);
			toast.show();
		}
		
	}

}
